<template>
    <Transition name="fade">
        <div v-if="visible" class="notification-container" :class="{ 'slide-in': visible }">
            <div class="notification-message">
                <slot>{{ currentMessage }}</slot>
            </div>
        </div>
    </Transition>
</template>

<script setup>
import { ref, onMounted, defineProps, defineExpose } from 'vue';

const props = defineProps({
    message: {
        type: String,
        default: ''
    },
    duration: {
        type: Number,
        default: 3000
    },
    autoClose: {
        type: Boolean,
        default: true
    }
});

const visible = ref(false);
const currentMessage = ref(props.message);
let timer = null;

const show = (msg) => {
    // 如果提供了消息，更新消息内容
    if (msg) {
        currentMessage.value = msg;
    } else {
        currentMessage.value = props.message;
    }

    // 清除现有的计时器
    if (timer) {
        clearTimeout(timer);
        timer = null;
    }

    // 显示通知
    visible.value = true;

    // 如果启用了自动关闭，设置定时器
    if (props.autoClose) {
        timer = setTimeout(() => {
            hide();
        }, props.duration);
    }
};

const hide = () => {
    visible.value = false;
    if (timer) {
        clearTimeout(timer);
        timer = null;
    }
};

// 组件卸载时清除计时器
onMounted(() => {
    return () => {
        if (timer) {
            clearTimeout(timer);
        }
    };
});

// 向父组件暴露方法
defineExpose({
    show,
    hide
});
</script>

<style scoped>
.notification-container {
    position: fixed;
    top: 20px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 9999;
}

.notification-message {
    background: rgba(164, 164, 164, 0.2);
    backdrop-filter: blur(200px);
    box-shadow: 0px 0px 1px 2px rgba(255, 255, 255, 0.3) inset;
    width: 264px;
    height: 60px;
    border-radius: 45px;
    font-weight: 400;
    font-size: 16px;
    color: #ffffff;
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    padding: 0 20px;
}

/* 过渡动画 */
.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.3s, transform 0.3s;
}

.fade-enter-from,
.fade-leave-to {
    opacity: 0;
    transform: translateX(-50%) translateY(-20px);
}

.slide-in {
    animation: slideIn 0.3s forwards;
}

@keyframes slideIn {
    from {
        opacity: 0;
        transform: translateX(-50%) translateY(-20px);
    }

    to {
        opacity: 1;
        transform: translateX(-50%) translateY(0);
    }
}
</style>